"""
Main entry point for the PROFIBUS test script.

This script can run either the PROFIBUS master or slave depending on command line arguments.
"""
import sys
import argparse
from profibus_master import ProfibusMaster
from profibus_slave import ProfibusSlave


def main():
    parser = argparse.ArgumentParser(description='PROFIBUS Test Script')
    parser.add_argument('role', choices=['master', 'slave'], 
                        help='Run as either master or slave')
    parser.add_argument('--device', type=str, 
                        help='Serial device to use (e.g., /dev/ttyUSB0)')
    parser.add_argument('--baud', type=int, default=187500,
                        help='Baud rate (default: 187500)')
    parser.add_argument('--address', type=int, default=1,
                        help='Slave address (for slave mode, default: 1)')
    parser.add_argument('--phy-type', type=str, default='serial',
                        help='Physical layer type (serial, dummy_slave) - default is serial for master, dummy_slave for slave')
    
    args = parser.parse_args()
    
    if args.role == 'master':
        print("Starting PROFIBUS DP Master...")
        
        # For master, we can use either serial or dummy phy
        phy_type = args.phy_type if args.phy_type in ['serial', 'dummy_slave'] else 'serial'
        device = args.device or '/dev/ttyUSB0'
        
        # Create a custom configuration file based on the specified phy_type
        import tempfile
        import os
        with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.cfg') as tmp_file:
            tmp_file.write(f"""[PROFIBUS]
debug = 1

[PHY]
type = {phy_type}
dev = {device}
baud = {args.baud}
rtscts = false
dsrdtr = false

[DP]
master_class = 1
master_addr = 2

[SLAVE_0]
name = ETA_X6_Slave
addr = {args.address}
gsd = eta_x6.gsd
sync_mode = false
freeze_mode = false
group_mask = 1
watchdog_ms = 5000
input_size = 6
output_size = 6
diag_period = 0
""")
            config_file = tmp_file.name
        
        master = ProfibusMaster(config_file=config_file)
        
        try:
            master.run()
        finally:
            # Clean up temp file
            if os.path.exists(config_file):
                os.unlink(config_file)
    
    elif args.role == 'slave':
        print(f"Starting PROFIBUS DP Slave at address {args.address}...")
        
        slave = ProfibusSlave(slave_addr=args.address)
        
        try:
            slave.run()
        except KeyboardInterrupt:
            print("\nSlave stopped by user.")
        except Exception as e:
            print(f"Error running slave: {e}")
            sys.exit(1)


if __name__ == "__main__":
    main()
